package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.AloneDao;
import com.baor.dao.DistributionLevelDao;
import com.baor.dao.DistributorDao;
import com.baor.dao.GoodsDao;
import com.baor.domain.AloneVo;
import com.baor.domain.DistributionLevelVo;
import com.baor.domain.DistributorVo;
import com.baor.domain.GoodsVo;
import com.baor.service.DistributionLevelService;
import com.baor.utils.AjaxResult;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;

@Service
public class DistributionLevelServiceImpl implements DistributionLevelService {

    @Autowired
    private DistributionLevelDao distributionLevelDao;

    @Autowired
    private DistributorDao distributorDao;

    @Autowired
    private AloneDao aloneDao;

    @Autowired
    private GoodsDao goodsDao;

    @Override
    public AjaxResult<?> insert(DistributionLevelVo vo) {
        if ( vo == null )
            return AjaxResult.error("不可为空",null);
        List<DistributionLevelVo> distributionLevelVos = distributionLevelDao.selectList(new LambdaQueryWrapper<DistributionLevelVo>()
                .eq(DistributionLevelVo::getSiteId,vo.getSiteId()));
        List<DistributionLevelVo> collect = distributionLevelVos.stream()
                .filter(x -> vo.getLevelGrade().equals(x.getLevelGrade()))
                .collect(Collectors.toList());
        if ( collect.size() > 0 )
            return AjaxResult.error("levelGrade不可重复",null);
        List<DistributionLevelVo> collect2 = distributionLevelVos.stream()
                .filter(x -> vo.getLevelName().equals(x.getLevelName()))
                .collect(Collectors.toList());
        if ( collect2.size() > 0 )
            return AjaxResult.error("levelName不可重复",null);
        Optional<DistributionLevelVo> first = distributionLevelVos.stream()
                .filter(x ->
                        vo.getFirstLevel().compareTo(x.getFirstLevel()) == 0
                                && vo.getSecondLevel().compareTo(x.getSecondLevel()) == 0
                ).findFirst();
        if ( first.isPresent() )
            return AjaxResult.error("请勿添加重复规则",null);
        int size = distributionLevelVos.stream().filter(
                x -> vo.getFirstLevel().compareTo(x.getFirstLevel()) < 0 && vo.getSecondLevel().compareTo(x.getSecondLevel()) < 0
        ).collect(Collectors.toList()).size();
        if ( size > 0 )
            return AjaxResult.error("请您分配更多比例",null);
        int insert = distributionLevelDao.insert(vo);
        QueryWrapper<AloneVo> wrapper = new QueryWrapper<>();
        wrapper.groupBy("goods_id")
                .select("goods_id");
        List<Map<String,Object>> list = aloneDao.selectMaps(wrapper);
        List<Object> goods = list.stream().map(x -> {
            AloneVo aloneVo = new AloneVo();
            aloneVo.setFirstLevel(vo.getFirstLevel());
            aloneVo.setSecondLevel(vo.getSecondLevel());
            aloneVo.setAloneMoney(BigDecimal.ZERO);
            aloneVo.setGoodsId(x.get("goods_id").toString());
            aloneVo.setDistributionLevelId(vo.getDistributionLevelId().toString());//
            aloneDao.insert(aloneVo);
            return x.get("goods_id");
        }).collect(Collectors.toList());
        return insert > 0 ? AjaxResult.success("添加默认分配等级后,下述商品的额外分销规则收到影响",goods) : AjaxResult.error() ;
    }

    @Override
    public AjaxResult<?> update(DistributionLevelVo vo) {
        if ( vo == null )
            return AjaxResult.error("不可为空",null);
        List<DistributionLevelVo> distributionLevelVos = distributionLevelDao.selectList(new LambdaQueryWrapper<DistributionLevelVo>()
                .eq(DistributionLevelVo::getSiteId,vo.getSiteId()));
        List<DistributionLevelVo> collect = distributionLevelVos.stream()
                .filter(x -> vo.getLevelGrade().equals(x.getLevelGrade()) && !vo.getDistributionLevelId().equals(x.getDistributionLevelId())).collect(Collectors.toList());
        if ( collect.size() > 0 )
            return AjaxResult.error("levelGrade不可重复",null);
        List<DistributionLevelVo> collect2 = distributionLevelVos.stream().filter(x -> vo.getLevelName().equals(x.getLevelName())&& !vo.getDistributionLevelId().equals(x.getDistributionLevelId())).collect(Collectors.toList());
        if ( collect2.size() > 0 )
            return AjaxResult.error("levelName不可重复",null);
        Optional<DistributionLevelVo> first = distributionLevelVos.stream()
                .filter(x ->
                        vo.getFirstLevel().compareTo(x.getFirstLevel()) == 0
                            && vo.getSecondLevel().compareTo(x.getSecondLevel()) == 0
                            && !vo.getDistributionLevelId().equals(x.getDistributionLevelId())
                ).findFirst();
        if ( first.isPresent() )
            return AjaxResult.error("请勿重复修改规则",null);
        int size = distributionLevelVos.stream().filter(
                x -> vo.getFirstLevel().compareTo(x.getFirstLevel()) < 0 && vo.getSecondLevel().compareTo(x.getSecondLevel()) < 0
        ).collect(Collectors.toList()).size();
        if ( size > 0 )
            return AjaxResult.error("请您分配更多比例",null);
        int insert = distributionLevelDao.updateById(vo);
        return insert > 0 ? AjaxResult.success() : AjaxResult.error() ;
    }

    @Override
    public AjaxResult<?> delete(Integer id) {//存在问题
        List<DistributionLevelVo> levelVos = distributionLevelDao.selectList(null);
        if ( levelVos.size() == 0 )
            return AjaxResult.error("已全部删除,请不要玩弄系统了qwq",null);
        Optional<DistributionLevelVo> first = levelVos.stream().filter(x -> !x.getDistributionLevelId().equals(id)).findFirst();
        if ( !first.isPresent() )
            return AjaxResult.error("怎么可能出现这个错误O.o",null);
        Long distributionLevelId = first.get().getDistributionLevelId();
        List<String> collect = distributorDao.selectList(new LambdaQueryWrapper<DistributorVo>()
                        .eq(DistributorVo::getDistributionLevelId, id)).stream()
                .map(x -> x.getUserId()).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("old",id);//distribution_level_id
        if ( levelVos.size() == 1 )
            map.put("new","0");
        else{
            map.put("new",distributionLevelId);
        }
        aloneDao.deleltByLevelId(first.get().getDistributionLevelId().toString());
//        aloneDao.deleteAloneByLevel(distributionLevelId);
        distributorDao.updateGrade(map);
        int i = distributionLevelDao.deleteById(id);
        return i > 0 ? AjaxResult.success("受到影响的分销商",collect) : AjaxResult.error() ;
    }

    @Override
    public AjaxResult<?> info(Integer id) {
        List<DistributionLevelVo> distributionLevelVos = distributionLevelDao
                .selectList(getMpj().eq(DistributionLevelVo::getDistributionLevelId,id));
        if ( distributionLevelVos.size() > 0 )
             return AjaxResult.success(distributionLevelVos.get(0));
        return AjaxResult.error("查不到(°_°)",null);
    }

    @Override
    public AjaxResult<?> aloneInsert(List<AloneVo> list) {
        System.out.println(list);
        if ( list.size() == 0 )
            return AjaxResult.error("怎么传空对象还有必要吗",null);
        GoodsVo goodsVo = goodsDao.selectById(list.get(0).getGoodsId());
        if ( goodsVo == null )
            return AjaxResult.error("亲,没有这个商品",null);
        if( goodsVo.getGoodsDistribution().equals("0") )
            return AjaxResult.error("亲,这个商品没有参与分销",null);
        if ( list.get(0).getAloneMoney() == null || "".equals(list.get(0).getAloneMoney()) )
            list.get(0).setAloneMoney(BigDecimal.ZERO);
        List<AloneVo> aloneVos = aloneDao.selectList(new LambdaQueryWrapper<AloneVo>().eq(AloneVo::getGoodsId, goodsVo.getGoodsId()));
        if ( aloneVos.size() > 0 )
            return AjaxResult.error("当前商品有独立的分销规则,请不要再添加,请修改");
        if ( list.size() == 1 && list.get(0).getAloneMoney().compareTo(BigDecimal.ZERO) > 0 ){//固定金额
            AloneVo aloneVo = list.get(0);
            aloneVo.setDistributionLevelId("0");
            aloneVo.setFirstLevel(BigDecimal.ZERO);
            aloneVo.setSecondLevel(BigDecimal.ZERO);
            int insert = aloneDao.insert(aloneVo);
            return insert > 0 ? AjaxResult.success() : AjaxResult.error() ;
        }
        AloneVo begin = list.get(0);
        for ( int i = 1 ; i < list.size() ; i++ ){
            AloneVo end = list.get(i);
            if ( begin.getFirstLevel() == null || begin.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                begin.setFirstLevel(BigDecimal.ZERO);
            if ( begin.getSecondLevel() == null || begin.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                begin.setSecondLevel(BigDecimal.ZERO);
            if ( end.getFirstLevel() == null || end.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                end.setFirstLevel(BigDecimal.ZERO);
            if ( end.getSecondLevel() == null || end.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                end.setSecondLevel(BigDecimal.ZERO);
            if ( end.getFirstLevel().compareTo(begin.getFirstLevel()) <= 0 && end.getSecondLevel().compareTo(begin.getSecondLevel()) <= 0 )
                return AjaxResult.error("请您给第"+(i+1)+"个分销规则分配更多的分销奖励",null);
            begin = end;
        }
        list.forEach(x -> {
            System.out.println(x);
            x.setAloneMoney(BigDecimal.ZERO);
            x.setGoodsId(goodsVo.getGoodsId().toString());
            aloneDao.insert(x);
        });
        goodsDao.updateDefault(goodsVo.getGoodsId());
        return AjaxResult.success();
    }

    @Override
    public AjaxResult<?> aloneInfo(Integer goodsId) {
        List<GoodsVo> goodsVos = goodsDao.selectList(new LambdaQueryWrapper<GoodsVo>()
                .eq(GoodsVo::getGoodsId, goodsId));
        if ( goodsVos.size() == 0 )
            return AjaxResult.error("有没有搞错,这货物我们这里都没有,你不要瞎说(−_−＃)",null);
//        List<GoodsVo> goodsVos2 = goodsDao.selectList(new LambdaQueryWrapper<GoodsVo>()
//                .eq(GoodsVo::getGoodsId, goodsId)
//                .eq(GoodsVo::getDefaultDistribution,1));
        if ( "0".equals(goodsVos.get(0).getGoodsDistribution()) )
            return AjaxResult.error("不好意思,这个商品没有参与分销,也就没有独立分销规则",null);
        if ( "0".equals(goodsVos.get(0).getDefaultDistribution()) )
            return AjaxResult.error("什么?你说这个商品参与分销了?不好意思,这个商品木有独立分销规则",null);
        return AjaxResult.success(aloneDao.selectList(
                getAloneMpj().eq(AloneVo::getGoodsId,goodsId)));
    }

    private MPJLambdaWrapper<AloneVo> getAloneMpj(){
        MPJLambdaWrapper<AloneVo> mpj = new MPJLambdaWrapper<>();
        mpj
                .selectAll(AloneVo.class)
                .selectAs(DistributionLevelVo::getLevelGrade,AloneVo::getLevelGrade)
                .selectAs(DistributionLevelVo::getLevelName,AloneVo::getLevelName)
                .leftJoin(DistributionLevelVo.class,DistributionLevelVo::getDistributionLevelId,AloneVo::getDistributionLevelId);
        return mpj;
    }

    @Override
    public AjaxResult<?> aloneUpdate(List<AloneVo> list) {
        if ( list.size() == 0 )
            return AjaxResult.error("怎么传空对象还有必要吗",null);
        GoodsVo goodsVo = goodsDao.selectById(list.get(0).getGoodsId());
        if ( goodsVo == null )
            return AjaxResult.error("亲,没有这个商品",null);
        if( goodsVo.getGoodsDistribution().equals("0") )
            return AjaxResult.error("亲,这个商品没有参与分销",null);
        if ( list.get(0).getAloneMoney() == null || "".equals(list.get(0).getAloneMoney()) )
            list.get(0).setAloneMoney(BigDecimal.ZERO);
        if ( list.size() == 1 && list.get(0).getAloneMoney().compareTo(BigDecimal.ZERO) > 0 ){//固定金额
            aloneDao.delete(new LambdaQueryWrapper<AloneVo>().eq(AloneVo::getGoodsId,list.get(0).getGoodsId()));
//            int i = aloneDao.updateById(list.get(0));?
            AloneVo aloneVo = list.get(0);
            aloneVo.setFirstLevel(BigDecimal.ZERO);
            aloneVo.setSecondLevel(BigDecimal.ZERO);
            aloneVo.setDistributionLevelId(null);
            aloneVo.setDistributionLevelId("0");
            int insert = aloneDao.insert(aloneVo);
            return insert > 0 ? AjaxResult.success() : AjaxResult.error() ;
        }
        AloneVo begin = list.get(0);
        if( begin.getAloneId() == null || "".equals(begin.getAloneId()) )
            return AjaxResult.error("我说改哪个呢这是(^_^)a",null);
        for ( int i = 1 ; i < list.size() ; i++ ){
            begin.setGoodsId(goodsVo.getGoodsId().toString());
            AloneVo end = list.get(i);
            if ( begin.getFirstLevel() == null || begin.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                begin.setFirstLevel(BigDecimal.ZERO);
            if ( begin.getSecondLevel() == null || begin.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                begin.setSecondLevel(BigDecimal.ZERO);
            if ( end.getFirstLevel() == null || end.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                end.setFirstLevel(BigDecimal.ZERO);
            if ( end.getSecondLevel() == null || end.getSecondLevel().compareTo(BigDecimal.ZERO) == 0 )
                end.setSecondLevel(BigDecimal.ZERO);
            if ( end.getFirstLevel().compareTo(begin.getFirstLevel()) <= 0 && end.getSecondLevel().compareTo(begin.getSecondLevel()) <= 0 )
                return AjaxResult.error("请您给第"+(i+1)+"个分销规则分配更多的分销奖励",null);
            begin = end;
        }
//        if( begin.getAloneId() == null || "".equals(begin.getAloneId()) )
//            return AjaxResult.error("我说改哪个呢这是",null);
        list.forEach(x -> {
            x.setAloneMoney(BigDecimal.ZERO);
            x.setGoodsId(goodsVo.getGoodsId().toString());
        });
        AloneVo remove = list.remove(0);
        aloneDao.updateById(remove);
        List<AloneVo> aloneVos = aloneDao.selectList(new LambdaQueryWrapper<AloneVo>().eq(AloneVo::getGoodsId, goodsVo.getGoodsId()));
        System.out.println("=================================");
        System.out.println(aloneVos.size());//1
        if ( aloneVos.size() > 1 )
            list.forEach(x -> aloneDao.updateById(x));
        else
            list.forEach( x -> {
                x.setAloneId(null);
                aloneDao.insert(x);
            });
        return AjaxResult.success();
    }


    private MPJLambdaWrapper<DistributionLevelVo> getMpj(){
        MPJLambdaWrapper<DistributionLevelVo> mpj = new MPJLambdaWrapper<>();
        mpj.selectAll(DistributionLevelVo.class);
        return mpj;
    }

    private Page<DistributionLevelVo> getPage(Map<String,Object> map){
        if ( map.get("pageIndex") == null || "".equals(map.get("pageIndex")) )
            map.put("pageIndex",1);
        if ( map.get("pageSize") == null || "".equals(map.get("pageSize")) )
            map.put("pageSize",10);
        Long pageIndex = Long.valueOf(map.get("pageIndex").toString());
        Long pageSize = Long.valueOf(map.get("pageSize").toString());
        Page<DistributionLevelVo> page = new Page<>(pageIndex,pageSize);
        return page;
    }

    @Override
    public AjaxResult<?> list(Map<String, Object> map) {
        Page<DistributionLevelVo> page = distributionLevelDao.selectPage(getPage(map),
                getMpj().eq(DistributionLevelVo::getSiteId,map.get("siteId")));
        List<DistributionLevelVo> records = page.getRecords();
        long pages = page.getPages();
        Map<String,Object> res = new HashMap<>();
        res.put("pageCount",pages);
        res.put("list",records);
        return AjaxResult.success(res);
    }






}
